<template>
  <a-card
    class="menu-content-preview-model"
    :bodyStyle="{ flex: 1, position: 'relative', overflow: 'hidden' }"
    :bordered="false"
    title="内容预览"
  >
    <a-spin
      v-if="loading || pathLoading"
      :spinning="loading"
      style="
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 10;
        background: rgba(255, 255, 255, 0.5);
      "
    />
    <div
      class="content"
      :style="loading ? { visibility: 'hidden' } : {}"
      ref="contentRef"
    >
      <div class="toolbar">
        <div>
          <select-face @change="onChangeFace" />
        </div>
        <div>
          <zoom-in @click="onClickZoomIn" />
        </div>
        <div>
          <zoom-out @click="onClickZoomOut" />
        </div>
        <div>
          <view-fit @click="onClickViewFit" />
        </div>
        <div>
          <full-screen-toggle :content="contentRef" v-if="contentRef" />
        </div>
        <div>
          <select-slice @change="onChangeSlice" :boundingBox="boundingBox" />
        </div>
        <div>
          <select-mode @change="onChangeMode" />
        </div>
      </div>
      <div class="preview">
        <preview-model
          v-if="!pathLoading && path"
          :path="path"
          :filename="filename"
          @complete="onComplete"
          ref="modelRef"
        />
      </div>
    </div>
  </a-card>
</template>
<script setup>
import { onMounted, onUnmounted, ref } from 'vue'
import PreviewModel from '@/components/preview-model.vue'
import SelectFace from './menu-content-preview-model-select-face.vue'
import ZoomIn from './menu-content-preview-model-button-zoom-in.vue'
import ZoomOut from './menu-content-preview-model-button-zoom-out.vue'
import ViewFit from './menu-content-preview-model-button-view-fit.vue'
import FullScreenToggle from './menu-content-preview-model-button-full-screen-toggle.vue'
import SelectMode from './menu-content-preview-model-select-mode.vue'
import SelectSlice from './menu-content-preview-model-select-slice.vue'

import { getFilePreview, rewriteURL } from '@/api/db.js'
import { useDbType } from '@/views/db-management/provide-context.js'
import { message as Message } from 'ant-design-vue'
/**
 * 外部参数
 */
let props = defineProps({
  data: {
    required: true,
  },
})
let dbType = useDbType()
let path = ref()
let filename = ref()
let pathLoading = ref(false)
onMounted(() => {
  pathLoading.value = true
  getFilePreview({ id: props?.data?.id }, dbType)
    .then(response => {
      path.value = URL.createObjectURL(response.data)
      filename.value = `${props?.data?.fileName}.${props?.data?.fileType}`
      pathLoading.value = false
    })
    .catch(async e => {
      try {
        let text = await e.text()
        let json = JSON.parse(text)
        Message.error(json.errorMessage || json.message || '文件加载失败')
      } catch (err) {
        Message.error('文件加载失败')
      }
      loading.value = false
    })
})

let loading = ref(true)
let modelRef = ref()
let boundingBox = ref()
let timer
function onComplete(e) {
  loading.value = false
  if (e) {
    return
  }
  // console.log(modelRef.value)
  let b = modelRef.value.getBoundingBox()
  timer = setInterval(() => {
    if (
      b.min.x !== Infinity &&
      b.min.y !== Infinity &&
      b.min.z !== Infinity &&
      b.max.x !== -Infinity &&
      b.max.y !== -Infinity &&
      b.max.z !== -Infinity
    ) {
      let lengthX = Math.abs(b.max.x - b.min.x)
      let lengthY = Math.abs(b.max.y - b.min.y)
      let lengthZ = Math.abs(b.max.z - b.min.z)
      boundingBox.value = {
        min: {
          x: b.min.x - lengthX * 0.1,
          y: b.min.y - lengthY * 0.1,
          z: b.min.z - lengthZ * 0.1,
        },
        max: {
          x: b.max.x + lengthX * 0.1,
          y: b.max.y + lengthY * 0.1,
          z: b.max.z + lengthZ * 0.1,
        },
      }
      clearInterval(timer)
    }
  }, 100)
}

function onChangeFace(type) {
  if (type === 'iso') {
    modelRef.value.lookIso()
  }
  if (type === 'front') {
    modelRef.value.lookFront()
  }
  if (type === 'back') {
    modelRef.value.lookBack()
  }
  if (type === 'left') {
    modelRef.value.lookLeft()
  }
  if (type === 'right') {
    modelRef.value.lookRight()
  }
  if (type === 'top') {
    modelRef.value.lookTop()
  }
  if (type === 'bottom') {
    modelRef.value.lookBottom()
  }
}

function onClickZoomIn() {
  modelRef.value.zoom(0.1)
}
function onClickZoomOut() {
  modelRef.value.zoom(-0.1)
}
function onClickViewFit() {
  modelRef.value.fitCameraToSelection()
}
function onChangeMode(types) {
  modelRef.value.meshVisible(false)
  modelRef.value.lineVisible(false)
  modelRef.value.pointVisible(false)

  types.forEach(type => {
    if (type === 'mesh') {
      modelRef.value.meshVisible(true)
    }
    if (type === 'line') {
      modelRef.value.lineVisible(true)
    }
    if (type === 'point') {
      modelRef.value.pointVisible(true)
    }
  })
}
function onChangeSlice([selectedFace, value, enable, visible, inversion]) {
  // console.log(selectedFace, value, enable, visible, inversion)

  modelRef.value.setClip(0, false, false)
  modelRef.value.setClip(1, false, false)
  modelRef.value.setClip(2, false, false)
  let plan
  if (selectedFace === 'XY') {
    plan = 2
  }
  if (selectedFace === 'XZ') {
    plan = 1
  }
  if (selectedFace === 'YZ') {
    plan = 0
  }
  modelRef.value.setClip(plan, enable, visible, value, inversion)
}

let contentRef = ref()
// let isFullScreen = ref(false)

// let { isFullscreen, enter, exit, toggle } = useFullscreen(contentRef)

// // document.addEventListener('keyup', esc)
// function onClickFullScreen() {
//   enter()
// }
// function onClickFullScreenClose() {
//   exit()
// }

// function isFullScreenFn() {
//   return !!(
//     document.fullscreen ||
//     document.mozFullScreen ||
//     document.webkitIsFullScreen ||
//     document.webkitFullScreen ||
//     document.msFullScreen
//   )
// }
// function setFullScreen() {
//   isFullScreen.value = isFullScreenFn()
// }
onMounted(() => {
  // window.addEventListener('resize', setFullScreen)
})
onUnmounted(() => {
  // window.removeEventListener('resize', setFullScreen)
  clearInterval(timer)
})
</script>
<style scoped lang="less">
.menu-content-preview-model {
  height: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .toolbar {
    display: flex;
    > * {
      margin-right: 26px;
    }
  }
  .content {
    display: flex;
    flex-direction: column;
    height: 100%;
    background-color: #fff;
    padding: 10px;
    box-sizing: border-box;
    .preview {
      margin-top: 10px;
      flex: 1;
      overflow: hidden;
    }
  }
}
</style>
